#pragma once
#include <iostream>
#include <memory>
#include <unistd.h>
#include "Socket.hpp"
#include "Log.hpp"
#include <sys/poll.h>

using namespace SocketModule;
using namespace LogModule;

class PollServer
{
    const static int size = 4096;
    const static int defaultfd = -1;
public:
    PollServer(int port)
        :_listensock(std::make_unique<Socket>(port))
        ,_isrunning(false)
    {
        _listensock->BuildTcpSocketMethod(port);
        for(int i = 0; i < size; i++)
        {
             _fds[i].fd = defaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listensock->Fd();
        _fds[0].events = POLLIN;
    }

    void Start()
    {
        _isrunning = true;
        int timeout = -1;
        while(_isrunning)
        {
            
            
            PrintFd();
            int n = poll(_fds, size, timeout);
            switch(n)
            {
                case -1:
                    LOG(LogLevel::ERROR) << "select error";
                    break;
                case 0:
                    LOG(LogLevel::INFO) << "time out...";
                    break;
                default:
                    // 说明某一/几个 套接字内有事件准备就绪
                    LOG(LogLevel::DEBUG) << "有事件就绪了..., n : " << n;
                    Dispatcher(); // 处理就绪的事件啊！
                    break;
            }
        }
    }

    void Dispatcher()
    {
        for(int i = 0; i < size; i++)
        {
            if(_fds[i].fd == defaultfd)
                continue;
            if(_fds[i].revents & POLLIN) //循环遍历辅助数组，并判断当前套接字中 事件是否准备就绪
            {
                if(_fds[i].fd== _listensock->Fd()) //说明当前准备就绪的是监听套接字，表示有新的连接请求
                {
                    Accepter();
                }
                else
                {
                    Recver(i);//否则表示其他套接字有事件，比如写 or 读
                }
            }
        }
    }

    void Accepter()
    {
        InetAddr client;
        int sockfd = _listensock->Accept(&client);
        if(sockfd >= 0)
        {
            int pos = 0;
            for(;pos < size;pos++)
            {
                if(_fds[pos].fd == defaultfd)
                    break;
            }
            if(pos == size)
            {
                close(sockfd);
            }
            else
            {
                _fds[pos].fd = sockfd;
                _fds[pos].events = POLLIN;
                _fds[pos].revents = 0;
            }
        }
    }

    void Recver(int pos)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[pos].fd,buffer,sizeof(buffer)-1,0);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@ "<< buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "clien quit...";
            // 1. 不要让select在关系这个fd了

            // 2. 关闭fd
            close(_fds[pos].fd);
            _fds[pos].fd = defaultfd;
            _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
        else 
        {
            LOG(LogLevel::ERROR) << "recv error";
            // 2. 关闭fd
            close(_fds[pos].fd);
            // 1. 不要让select在关系这个fd了
            _fds[pos].fd = defaultfd;
            _fds[pos].events = 0;
            _fds[pos].revents = 0;
        }
    }

    void PrintFd()
    {
        std::cout << "_fd_array[]: ";
        for (int i = 0; i < size; i++)
        {
            if (_fds[i].fd == defaultfd)
                continue;
            std::cout << _fds[i].fd << " ";
        }
        std::cout << "\r\n";
    }
      ~PollServer()
    {
    }
private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;
    struct pollfd _fds[size];
};